<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Play;
use App\Models\Section;
use Dingo\Api\Exception\StoreResourceFailedException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class TemplateController extends Controller
{
    /**
     * @SWG\Get(
     *     summary="模板列表",
     *     path="/template",
     *     description="获取所有列表",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="page",
     *         in="query",
     *         description="页码[default:1]",
     *         required=false,
     *         type="integer"
     *     ),
     *     @SWG\Parameter(
     *         name="per_page",
     *         in="query",
     *         description="每页条数[default:15]",
     *         required=false,
     *         type="integer"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     )
     * )
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function index(Request $request)
    {
        $perPage = intval($request->get('per_page'));

        $paginate = Play::where(['is_template' => 1])
            ->orderBy('id', 'desc')
            ->paginate($perPage, ['id', 'title', 'thumb', 'updated_at', 'views']);

        return $paginate;
    }

    /**
     * @SWG\Get(
     *     summary="模板详情",
     *     path="/template/{id}",
     *     description="模板详情",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="授权令牌[Bearer <token>]",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Parameter(
     *         name="id",
     *         in="path",
     *         description="剧本id",
     *         required=true,
     *         type="integer"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     )
     * )
     *
     * @param $id
     *
     * @return array
     */
    public function show($id)
    {
        $play = Play::findOrFail($id, ['id', 'title', 'description', 'thumb', 'updated_at', 'views'])->toArray();
        $play['sections'] = Section::where(['play_id' => $id])->first(['id', 'title', 'sequence', 'css', 'properties'])->toArray();
        foreach ($play['sections'] as &$section) {
            $section['css'] = json_decode($section['css']);
            $section['properties'] = json_decode($section['properties']);
        }

        return $play;
    }

}
